package xyz.xtgl.security.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author liubo
 * @created 2019-12-13 17:04
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            //跨站域名伪造
            .csrf().disable()
            .authorizeRequests()
//                .antMatchers("/r/r1").hasAuthority("p1")
//                .antMatchers("/r/r2").hasAuthority("p2")
                // 所有/r/** 的请求必须登录
                .antMatchers("/r/**").authenticated()
                //其他都可以请求 . 放行
                .anyRequest().permitAll()
                .and()
                //允许表单登录
            .formLogin()
                //登录页面
                .loginPage("/login-view")
                //登录处理URL
                .loginProcessingUrl("/login")
                //自定义成功跳转页面
                .successForwardUrl("/login-success")
                .and()
             .sessionManagement()
                //如果是分布式这里需要设置成不创建session, 因为这是使用token
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login-view?logout=true")






        ;
    }

}
